#include "Map.h"
#include "TextureManager.h"

Map::Map(SDL_Renderer* pRenderer)
{
	m_pRenderer = pRenderer;
	m_locationTitles = NULL;
}

Map::~Map()
{
	delete[] m_locationTitles;
}

void Map::loadFile(char* _filename)
{
	std::ifstream fileDataMap(_filename);
	fileDataMap >> m_fileName;

	char* fileNameTxt = new char[m_fileName.length()];
	std::size_t length = m_fileName.copy(fileNameTxt, m_fileName.length(), 0);
	fileNameTxt[length] = '\0';

	m_sprite_map.loadFile(fileNameTxt);
	TheTextureManager::Instance()->add(m_sprite_map, m_pRenderer);

	fileDataMap >> m_recycle;
	fileDataMap >> m_infoTitles.x;
	fileDataMap >> m_recycle;
	fileDataMap >> m_infoTitles.y;
	fileDataMap >> m_recycle;
	fileDataMap >> m_infoTitles.width;
	fileDataMap >> m_recycle;
	fileDataMap >> m_infoTitles.height;
	fileDataMap >> m_recycle;
	fileDataMap >> m_recycle;
	fileDataMap >> m_infoTitles.colum;
	fileDataMap >> m_recycle;
	fileDataMap >> m_infoTitles.row;
	fileDataMap >> m_recycle;
	
	m_number_titles = m_infoTitles.row*m_infoTitles.colum;
	m_locationTitles = new int[m_number_titles];
	for (int index = 0; index < m_number_titles; index++)
	{
		fileDataMap >> m_locationTitles[index];
	}
}

void Map::update()
{

}

void Map::render()
{
	//int id = 0;
	
	//TheTextureManager::Instance()->drawParallax(m_sprite_map, id, m_pRenderer);
	int _w = m_infoTitles.width / m_infoTitles.colum;
	int _h = m_infoTitles.height / m_infoTitles.row;
	

	for (int index = 0; index < m_number_titles; index++)
	{
		//for (int j = 0; j < m_infoTitles.row; j++)
		//{
			int ox = index / m_infoTitles.colum;
			int oy = index % m_infoTitles.colum;
			int y = ox * _w;
			int x = oy * _h;
			int id = m_locationTitles[index];
			m_sprite_map.setDrawingCoordinates(x, y, _w, _h, id);
			

			TheTextureManager::Instance()->drawParallax(m_sprite_map, id, m_pRenderer);
		//}
		
	}
}

int Map::findIdTitles(int &_x, int &_y)
{
	int _w = m_infoTitles.width / m_infoTitles.colum;
	int _h = m_infoTitles.height / m_infoTitles.row;
	int x = _x / _w;
	int y = _y / _h;

	return (y*m_infoTitles.colum + x);
}